package com.lsw.jgyf.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.lsw.dialog.PubDialogUtil;
import com.lsw.jgyf.R;
import com.lsw.jgyf.adapter.PopupWindowSortAdapter;
import com.lsw.jgyf.model.JsonBean;
import com.lsw.jgyf.model.PopupWindowSortModel;
import com.lsw.jgyf.ui.activity.MainActivity;
import com.lsw.jgyf.ui.base.fragment.BaseFragment;
import com.lsw.util.AppManager;
import com.lsw.util.DensityUtil;
import com.lsw.util.JsonFileReader;
import com.lsw.util.LogUtils;
import com.lsw.util.StringUtil;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by lsw on 2018/7/8.
 */

public class RegisterDianzhangFragment extends BaseFragment<RegisterDianzhangFragmentPresenter> implements RegisterDianzhangFragmentContract.View, View.OnClickListener {
    PubDialogUtil dialogUtil;
    @BindView(R.id.tv_register)
    TextView tv_register;
    @BindView(R.id.ll_mendiandianhua)
    LinearLayout ll_mendiandianhua;
    @BindView(R.id.et_mendiandianhua)
    EditText et_mendiandianhua;
    @BindView(R.id.ll_quyu)
    LinearLayout ll_quyu;
    @BindView(R.id.tv_quyu)
    TextView tv_quyu;
    @BindView(R.id.et_bianhao)
    EditText et_bianhao;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.et_address)
    EditText et_address;
    @BindView(R.id.et_kongzhiren)
    EditText et_kongzhiren;
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_phone2)
    EditText et_phone2;
    @BindView(R.id.et_dianzhang)
    EditText et_dianzhang;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.tv_fasong)
    TextView tv_fasong;
    @BindView(R.id.et_pass)
    EditText et_pass;
    @BindView(R.id.et_password)
    EditText et_password;


    @Override
    protected int getlayoutId() {
        return R.layout.fragment_register_dianzhang;
    }

    @Override
    protected void initInjector() {
        mFragmentComponent.inject(this);
    }

    @Override
    protected void initEventAndData() {
        ll_mendiandianhua.setOnClickListener(this);
        ll_quyu.setOnClickListener(this);
        tv_register.setOnClickListener(this);
        tv_fasong.setOnClickListener(this);
        dialogUtil = new PubDialogUtil(mContext);
        mPresenter.getAddress(false);
    }

    @Override
    protected void lazyLoadData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_register:
                mPresenter.register(et_bianhao.getText().toString().trim(), et_name.getText().toString().trim(), et_mendiandianhua.getText().toString().trim(), province_id, city_id, area_id, et_address.getText().toString().trim(), et_kongzhiren.getText().toString().trim(), et_phone.getText().toString().trim(), et_dianzhang.getText().toString().trim(), et_phone2.getText().toString().trim(), et_code.getText().toString().trim(), et_pass.getText().toString().trim(), et_password.getText().toString().trim());
                break;
            case R.id.ll_mendiandianhua:
                break;
            case R.id.ll_quyu:
                if (options1Items.size() > 0) {
                    pvOptions.show();
                } else
                    mPresenter.getAddress(true);
                break;
            case R.id.tv_fasong:
                mPresenter.sendCode(et_phone2.getText().toString().trim(), "2");
                break;
        }
    }

    @Override
    public void setData() {

    }

    @Override
    public void sendSucess() {
        startCountDown(60000);
    }

    @Override
    public void setAddress(List<JsonBean> list, boolean isdialog) {
        if (list.size() > 0)
            showDialog((ArrayList<JsonBean>) list, isdialog);
    }

    @Override
    public void registerSucess() {
        dialogUtil.showDialogtitleText("注册成功", "请耐心等待审核通过\n极果优分", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(mContext, MainActivity.class);
//                startActivity(intent);
                getActivity().finish();
            }
        }, false, "");
    }

//    PopupWindow popupWindow;
//    private List<PopupWindowSortModel> list1 = new ArrayList<>();
//    PopupWindowSortAdapter popupWindowSortAdapter;
//    View popupWindow_view;
//    ListView listView;
//
//    /**
//     * 创建PopupWindow
//     */
//    protected void initPopuptWindow(List<PopupWindowSortModel> list1, View view_bottom, int ispos) {
//        // TODO Auto-generated method stub
//        // 获取自定义布局文件activity_popupwindow_left.xml的视图
//        popupWindow_view = LayoutInflater.from(mContext).inflate(R.layout.popupwindow_sort, null,
//                false);
//        listView = popupWindow_view.findViewById(R.id.listview);
//        popupWindowSortAdapter = new PopupWindowSortAdapter(mContext);
//        popupWindowSortAdapter.setData(list1);
//        listView.setAdapter(popupWindowSortAdapter);
//        listView.setOnItemClickListener((adapterView, view, i, l) -> {
//            PopupWindowSortModel item = popupWindowSortAdapter.getItem(i);
//            if (ispos == 1)
//                tv_quyu.setText(item.getName());
//            else
//                tv_mendiandianhua.setText(item.getName());
//            popupWindow.dismiss();
//        });
////        }
//        popupWindow = new PopupWindow(popupWindow_view, DensityUtil.getWidth(mContext) - DensityUtil.dip2px(mContext, 60), LinearLayout.LayoutParams.WRAP_CONTENT, true);
////        // 设置动画效果
////        popupWindow.setAnimationStyle(R.style.AnimationFade);
//        // 点击其他地方消失
//        if (Build.VERSION.SDK_INT < 24) {
//            popupWindow.showAsDropDown(view_bottom);
//        } else {
//            // 适配 android 7.0
//            int[] location = new int[2];
//            view_bottom.getLocationOnScreen(location);
//            int x = location[0];
//            int y = location[1];
//            popupWindow.showAtLocation(view_bottom, Gravity.NO_GRAVITY, DensityUtil.dip2px(mContext, 30), y + view_bottom.getHeight() + DensityUtil.dip2px(mContext, 5));
//        }
//        popupWindow.setOnDismissListener(() -> {
//            popupWindow = null;
//        });
//    }

    private CountDownTimer countDownTimer;

    /**
     * 倒计时
     *
     * @param time
     */
    private void startCountDown(long time) {
        tv_fasong.setEnabled(false);
//        tv_fasong.setTextColor(mContext.getResources().getColor(R.color.gray));
        countDownTimer = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv_fasong.setText((millisUntilFinished / 1000) + "s后重新发送");
            }

            @Override
            public void onFinish() {
//                tv_fasong.setText(mContext.getResources().getString(R.string.verify_code));
//                tv_fasong.setBackground(mContext.getResources().getDrawable(R.drawable.round_blue_r));
//                tv_fasong.setTextColor(mContext.getResources().getColor(R.color.blue));
                tv_fasong.setText("重新发送");
                tv_fasong.setEnabled(true);
            }
        };
        countDownTimer.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null)
            countDownTimer.cancel();
    }

    /*默认选中项*/
    int defaultpos;
    /*省市区数据集合*/
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<JsonBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<JsonBean>>> options3Items = new ArrayList<>();
    private String province_id, city_id, area_id;

    OptionsPickerView pvOptions;

    public void showDialog(ArrayList<JsonBean> list, boolean isdialog) {

        if (options1Items.size() == 0) {
            initJsonData(list);
        }
        LogUtils.i("lsw", "list.size===" + list.size());
        pvOptions = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getAreaname() + " "
                        + options2Items.get(options1).get(option2).getAreaname() + " "
                        + options3Items.get(options1).get(option2).get(options3).getAreaname();
                if (options1Items.size() > 0)
                    province_id = options1Items.get(options1).getId();
                else province_id = "0";
                if (options1Items.get(options1).getChildren().size() > 0)
                    city_id = options1Items.get(options1).getChildren().get(option2).getId();
                else city_id = "0";
                if (options1Items.get(options1).getChildren().get(option2).getChildren().size() > 0)
                    area_id = options1Items.get(options1).getChildren().get(option2).getChildren().get(options3).getId();
                else area_id = "0";
                LogUtils.i("lsw", "province_id=" + province_id + ",city_id=" + city_id + ",area_id=" + area_id);
                tv_quyu.setText(tx);
            }
        })
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
//                .setTitleText("城市选择")//标题
                .setSubCalSize(18)//确定和取消文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(R.color.black)//确定按钮文字颜色
                .setCancelColor(R.color.black)//取消按钮文字颜色
                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
                .setContentTextSize(18)//滚轮文字大小
                .setLinkage(true)//设置是否联动，默认 true
                .setLabels("", "", "")//设置选择的三级单位
                .isCenterLabel(false) //是否只显示中间选中项的 label 文字，false 则每项 item 全部都带有 label。
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(defaultpos, 0, 0)  //设置默认选中项
                .setOutSideCancelable(false)//点击外部 dismiss default true
                .isDialog(false)//是否显示为对话框样式
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//添加数据源
        if (isdialog)
            pvOptions.show();
    }

    /**
     * 解析数据
     */
    private void initJsonData(ArrayList<JsonBean> jsonBean) {

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            if (TextUtils.equals("四川省", jsonBean.get(i).getAreaname()))
                defaultpos = i;
            ArrayList<JsonBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<JsonBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getChildren().size(); c++) {//遍历该省份的所有城市
                JsonBean city = new JsonBean();
                city.setAreaname(jsonBean.get(i).getChildren().get(c).getAreaname());
                city.setId(jsonBean.get(i).getChildren().get(c).getId());
                CityList.add(city);//添加城市

                ArrayList<JsonBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getChildren().get(c).getChildren() == null
                        || jsonBean.get(i).getChildren().get(c).getChildren().size() == 0) {
                    JsonBean area = new JsonBean();
                    area.setAreaname("");
                    area.setId("0");
                    City_AreaList.add(area);
                } else {

                    for (int d = 0; d < jsonBean.get(i).getChildren().get(c).getChildren().size(); d++) {//该城市对应地区所有数据
                        JsonBean area = new JsonBean();
                        area.setAreaname(jsonBean.get(i).getChildren().get(c).getChildren().get(d).getAreaname());
                        area.setId(jsonBean.get(i).getChildren().get(c).getChildren().get(d).getId());
                        City_AreaList.add(area);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

    }


}
